package org.ycx.upms.web.controller;

import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ycx.common.constants.RespCode;
import org.ycx.common.dto.RespMSG;
import org.ycx.common.validator.NotNullValidator;
import org.ycx.common.validator.ValidationErrorToString;
import org.ycx.upms.common.constants.SecurityConstants;
import org.ycx.upms.dao.model.SecPermission;
import org.ycx.upms.dao.model.SecPermissionExample;
import org.ycx.upms.dao.model.SecSystem;
import org.ycx.upms.dao.model.SecSystemExample;
import org.ycx.upms.service.ISecPermissionService;
import org.ycx.upms.service.ISecSystemService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SecPermissioncontroller
 * Created by yang on 2017-07-19 16:25:40.
 */
@Controller
@RequestMapping("/sec/permission")
public class SecPermissionController {

    private static Logger _log = LoggerFactory.getLogger(SecPermissionController.class);

    private static final String PRE = "sec/permission/";

    @Autowired
    private ISecPermissionService service;

    @Autowired
    private ISecSystemService systemService;

    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/index.html")
    public String indexPage(ModelMap modelMap) {
        return PRE + "index";
    }

    /**
     * 新增页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping("/create.html")
    public String createPage(ModelMap modelMap) {
        List<SecSystem> systems = this.systemService.selectByExample(new SecSystemExample());
        modelMap.put("systems",systems);
        return PRE + "create";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/update/{id}.html")
    public String updatePage(@PathVariable("id") int id, ModelMap modelMap) {
        SecPermission bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean", bean);
        return PRE + "update";
    }

    /**
     * 更新页面
     *
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/detail/{id}.html")
    public String detailPage(@PathVariable("id") int id, ModelMap modelMap) {
        SecPermission bean = this.service.selectByPrimaryKey(id);
        modelMap.put("bean", bean);
        return PRE + "detail";
    }

    /**
     * 新增功能
     *
     * @param bean
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public RespMSG create(SecPermission bean, HttpSession session) {
        ComplexResult result = FluentValidator.checkAll()
                .on(bean.getName(), new NotNullValidator("权限名称"))
                .on(bean.getValue(), new NotNullValidator("权限值"))
                .on(bean.getUri(), new NotNullValidator("资源路径"))
                .on(bean.getIcon(), new NotNullValidator("资源图标"))
                .on(bean.getSystemId()+"",new NotNullValidator("所属系统"))
                .on(bean.getState(), new NotNullValidator("资源状态"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(), "\n\r"));
            return error;
        }
        bean.setCreateTs(new Date());
        bean.setUpdateTs(new Date());
        bean.setCreateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        bean.setUpdateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        int count = service.insert(bean);
        return new RespMSG(RespCode.SUCCESS);
    }

    /**
     * 更新功能
     *
     * @param id
     * @param bean
     * @return
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public RespMSG update(@PathVariable("id") int id, SecPermission bean, HttpSession session) {
        //TODO 验证数据，验证完成，设定主键为id
        ComplexResult result = FluentValidator.checkAll()
                .on(bean.getName(), new NotNullValidator("权限名称"))
                .on(bean.getValue(), new NotNullValidator("权限值"))
                .on(bean.getUri(), new NotNullValidator("资源路径"))
                .on(bean.getIcon(), new NotNullValidator("资源图标"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            RespMSG error = new RespMSG(RespCode.FAIL);
            error.setDesc(ValidationErrorToString.errorToString(result.getErrors(), "\n\r"));
            return error;
        }
        bean.setUpdateTs(new Date());
        bean.setUpdateUid((Integer) session.getAttribute(SecurityConstants.CURRENT_UID));
        int count = service.updateByPrimaryKeySelective(bean);
        return new RespMSG(RespCode.SUCCESS);
    }

    /**
     * 删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public RespMSG delete(@PathVariable("ids") String ids) {
        int count = service.deleteByPrimaryKeys(ids);
        return new RespMSG(RespCode.SUCCESS);
    }


    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(Integer pid) {
        SecPermissionExample beanExample = new SecPermissionExample();
        if(null !=pid){
            beanExample.createCriteria().andPidEqualTo(pid);
        }else{
            beanExample.createCriteria().andPidIsNull();
        }
        //TODO 模糊查询定义
        List<SecPermission> rows = service.selectByExample(beanExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        return result;
    }
}
